#!/bin/zsh

IN_FILE="$1"

OPTIND=2
while getopts ":p:q:f:" arg; do
	case "$arg" in
    p) P_OPT="$OPTARG"
       ;;
    q) Q_OPT="$OPTARG"
       ;;
    f) VF_ARGS="-vf \"$OPTARG\""
       ;;
    \?)echo "USAGE"
       exit
       ;;
    :) echo "USAGE"
       exit
       ;;
    *) :
       ;;
	esac
done
shift $((OPTIND -1))
case "$P_OPT" in
	1) POWER=2
     ;;
	2) POWER=4
     ;;
	3) POWER=8
     ;;
	4) POWER=16
     ;;
	*) POWER=16
     echo "[ERR] Power option not set, using best..."
     ;;
esac
case "$Q_OPT" in
	1) QUALITY=23
     ;;
	2) QUALITY=14
     ;;
	3) QUALITY=8
     ;;
	4) QUALITY=1
     ;;
	*) QUALITY=1
     echo "[ERR] Quality option not set, using best..."
     ;;
esac

echo "------------------"
echo "POWER> $POWER"
echo "QUALITY> $QUALITY"
echo "VF_ARGS> $VF_ARGS"
echo "------------------"

V_LEN=$(ffprobe -v error \
          -show_entries format=duration \
          -of default=noprint_wrappers=1:nokey=1 "$IN_FILE" \
          | cut -d '.' -f1)
FFPX_NUM=$(openssl rand -hex 5)

concat()
{
	for file in ./ffmpegtmp/*.mp4; do
		echo "$file" >> ./ffmpegtmp/concatt.txt
	done

	cut -d '/' -f3 < ./ffmpegtmp/concatt.txt \
		| sort -n  | sed "s|^|file '|g" \
		| sed "s|$|'|g" > ./ffmpegtmp/concat.txt
	rm ./ffmpegtmp/concatt.txt

	ffmpeg -f concat \
		-safe 0 \
		-i ./ffmpegtmp/concat.txt \
		-c:a copy \
		./fup_"$FFPX_NUM".mp4
}



mkdir -p ./ffmpegtmp

i=0
k=0.0
CLIP_N=$(bc <<< "$V_LEN / 0.25")

while [ $i -le "$CLIP_N" ]; do
    for j in $(seq "$POWER"); do
        MAR+=(ffmpeg -ss "$k" \
            -t 0.25 \
            -i "$IN_FILE" \
            -an \
            -c:v libx264 \
            "$VF_ARGS" \
            -crf "$QUALITY" \
            -pix_fmt yuv420p \
            ./ffmpegtmp/"$i".mp4 \& )
        i=$(bc <<< "$i + 1")
        k=$(bc <<< "$k + 0.25" | awk '{printf "%f", $0}')
    done

    MAR+=("wait")

    eval "${MAR[*]}"

    unset MAR
done

concat
ffmpeg -i ./fup_"$FFPX_NUM".mp4 \
	-i "$IN_FILE" \
	-c:a copy \
	./fup_"$FFPX_NUM"F.mp4

rm -rf ./ffmpegtmp


